<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;

class ContactService extends BaseService
{
    public function contactRecruitList(array $input, int $page, int $limit, string $sortField, string $orderRule,
                                       array $userTableColumns = ['*'], array $verifyTableColumns = ['*'], array $recruitTableColumns = ['*'])
    {
        $userId = $input['user_id'];
        $query = User::query()
            ->find($userId)
            ->contactRecruits()
            ->with(['user' => function(BelongsTo $query) use ($userTableColumns) {
                $query->select($userTableColumns);
            }, 'user.verifyInfo'=> function(HasOne $query) use ($verifyTableColumns) {
                $query->select($verifyTableColumns);
            }]);

        if (!empty($sortField) && !empty($orderRule)) {
            $query = $query->orderBy($sortField, $orderRule);
        }

        $paginator = $query->paginate($limit, $recruitTableColumns, 'page', $page);
        $paginates = $this->optimizationPaginate($paginator);
        $result = [];
        foreach ($paginates as $key => $paginate) {
            if ($key == 'list') {
                $contacts = collect($paginate)->toArray();
                foreach ($contacts as $contact) {
                    $contactTime = $contact['pivot']['contact_time'];
                    $index = array_search($contactTime, array_column($result, 'contact_time'));
                    $item = [
                        'id'            => $contact['id'],
                        'city'          => $contact['city'],
                        'title'         => $contact['title'],
                        'created_at'    => $contact['created_at'],
                        'nick_name'     => $contact['user']['nickname'],
                        'contact_phone' => $contact['contact_phone'],
                        'avatar'        => $contact['user']['avatar'],
                        'verify_info'   => $contact['user']['verify_info'],
                    ];
                    if ($index !== false) {
                        $result[$index]['list'][] = $item;
                    } else {
                        $result[] = [
                            'contact_time' => $contactTime,
                            'list'         => [$item]
                        ];
                    }
                }
            }
        }
        return array_merge($paginates, ['list' => $result]);
    }
}
